<?php

$data = array();
$data['errors'] = array();

if (isset($_GET['user_id'])) {
    $data['user']['user_id'] = (int) ($_GET['user_id']);
    $userSql = 'SELECT * FROM users WHERE user_id = ' . $data['user']['user_id'];
    $userQuery = mysqli_query($connection, $userSql);

    if (mysqli_num_rows($userQuery) > 0) {
        $user = mysqli_fetch_assoc($userQuery);
        $data['user']['username'] = $user['username'];
        
        $userCommentsSql = 'SELECT u.username, c.book_id, b.book_title, c.content, c.creation_date
                            FROM comments as c
                            INNER JOIN books as b ON b.book_id = c.book_id
                            INNER JOIN users as u ON u.user_id = c.user_id
                            WHERE c.user_id = ' . $data['user']['user_id'] .
                            ' ORDER BY c.creation_date DESC';
        $commentsQuery = mysqli_query($connection, $userCommentsSql);

        $data['user']['comments'] = array();
        $comments = array();
        while ($row = mysqli_fetch_assoc($commentsQuery)) {
            $comments['book_id'] = $row['book_id'];
            $comments['book_title'] = $row['book_title'];
            $comments['creation_date'] = $row['creation_date'];
            $comments['content'] = $row['content'];
            $data['user']['comments'][] = $comments;
        }
    } else {
        $data['errors'][] = 'Този потребител не съществува';
    }
} else {
    header('Location: index.php');
    exit();
}

$data['title'] = 'Потребител';
render($data, 'templates/user_public.php');